import { prisma } from '../db'
import bcrypt from 'bcryptjs'
import type { User, UserRole, ProductConfig } from '@prisma/client'

export interface CreateSubAdminData {
  email: string
  username: string
  password: string
}

export interface CreateCustomerData {
  email: string
  username: string
  password: string
}

export interface UpdateUserData {
  email?: string
  username?: string
  isActive?: boolean
  role?: UserRole
}

export interface ProductConfigInput {
  id?: number
  coinAmount: number
  productId: number
  isActive: boolean
  description?: string
  sortOrder: number
}

export class AdminService {
  private static readonly SALT_ROUNDS = 12

  /**
   * 检查用户是否为管理员
   */
  static async checkAdminPermission(userId: number): Promise<boolean> {
    const user = await prisma.user.findUnique({
      where: { id: userId }
    })
    return user?.role === 'ADMIN' || user?.role === 'SUB_ADMIN'
  }

  /**
   * 检查用户是否为超级管理员
   */
  static async checkSuperAdminPermission(userId: number): Promise<boolean> {
    const user = await prisma.user.findUnique({
      where: { id: userId }
    })
    return user?.role === 'ADMIN'
  }

  /**
   * 创建子管理员
   */
  static async createSubAdmin(adminId: number, data: CreateSubAdminData): Promise<Omit<User, 'password'>> {
    // 检查创建者权限
    const isAdmin = await this.checkSuperAdminPermission(adminId)
    if (!isAdmin) {
      throw new Error('Only super admin can create sub-admins')
    }

    // 检查邮箱是否已存在
    const existingUser = await prisma.user.findUnique({
      where: { email: data.email }
    })
    if (existingUser) {
      throw new Error('Email already exists')
    }

    // 检查用户名是否已存在
    const existingUsername = await prisma.user.findUnique({
      where: { username: data.username }
    })
    if (existingUsername) {
      throw new Error('Username already exists')
    }

    // 加密密码
    const hashedPassword = await bcrypt.hash(data.password, this.SALT_ROUNDS)

    // 创建子管理员
    const subAdmin = await prisma.user.create({
      data: {
        email: data.email,
        username: data.username,
        password: hashedPassword,
        role: 'SUB_ADMIN',
        createdByAdminId: adminId
      }
    })

    // 记录审计日志
    await this.logAuditAction(
      adminId,
      'CREATE_SUB_ADMIN',
      'User',
      `Created sub-admin: ${subAdmin.email}`,
      subAdmin.id
    )

    const { password: _, ...subAdminWithoutPassword } = subAdmin
    return subAdminWithoutPassword
  }

  /**
   * 创建普通用户（客户）
   */
  static async createCustomer(adminId: number, data: CreateCustomerData): Promise<Omit<User, 'password'>> {
    // 检查管理员权限
    const isAdmin = await this.checkAdminPermission(adminId)
    if (!isAdmin) {
      throw new Error('Admin permission required')
    }

    // 检查邮箱是否已存在
    const existingUser = await prisma.user.findUnique({
      where: { email: data.email }
    })
    if (existingUser) {
      throw new Error('Email already exists')
    }

    // 检查用户名是否已存在
    const existingUsername = await prisma.user.findUnique({
      where: { username: data.username }
    })
    if (existingUsername) {
      throw new Error('Username already exists')
    }

    // 加密密码
    const hashedPassword = await bcrypt.hash(data.password, this.SALT_ROUNDS)

    // 创建普通用户
    const customer = await prisma.user.create({
      data: {
        email: data.email,
        username: data.username,
        password: hashedPassword,
        role: 'USER',
        createdByAdminId: adminId
      }
    })

    // 记录审计日志
    await this.logAuditAction(
      adminId,
      'CREATE_CUSTOMER',
      'User',
      `Created customer: ${customer.email}`,
      customer.id
    )

    const { password: _, ...customerWithoutPassword } = customer
    return customerWithoutPassword
  }

  /**
   * 获取所有用户列表
   */
  static async getAllUsers(adminId: number, page: number = 1, limit: number = 20): Promise<{
    users: Omit<User, 'password'>[]
    total: number
    page: number
    totalPages: number
  }> {
    // 检查管理员权限
    const isAdmin = await this.checkAdminPermission(adminId)
    if (!isAdmin) {
      throw new Error('Admin permission required')
    }

    const skip = (page - 1) * limit

    const [users, total] = await Promise.all([
      prisma.user.findMany({
        skip,
        take: limit,
        orderBy: { createdAt: 'desc' },
        select: {
          id: true,
          email: true,
          username: true,
          role: true,
          isActive: true,
          googleId: true,
          avatar: true,
          payoutPassword: true,
          lastLoginAt: true,
          createdAt: true,
          updatedAt: true,
          createdByAdminId: true,
          createdByAdmin: {
            select: {
              id: true,
              username: true,
              email: true
            }
          }
        }
      }),
      prisma.user.count()
    ])

    return {
      users,
      total,
      page,
      totalPages: Math.ceil(total / limit)
    }
  }

  /**
   * 获取子管理员列表
   */
  static async getSubAdmins(adminId: number): Promise<Omit<User, 'password'>[]> {
    // 检查超级管理员权限
    const isAdmin = await this.checkSuperAdminPermission(adminId)
    if (!isAdmin) {
      throw new Error('Super admin permission required')
    }

    const subAdmins = await prisma.user.findMany({
      where: {
        role: 'SUB_ADMIN',
        createdByAdminId: adminId
      },
      select: {
        id: true,
        email: true,
        username: true,
        role: true,
        isActive: true,
        googleId: true,
        avatar: true,
        payoutPassword: true,
        lastLoginAt: true,
        createdAt: true,
        updatedAt: true,
        createdByAdminId: true
      },
      orderBy: { createdAt: 'desc' }
    })

    return subAdmins
  }

  /**
   * 更新用户信息
   */
  static async updateUser(adminId: number, userId: number, data: UpdateUserData): Promise<Omit<User, 'password'>> {
    // 检查管理员权限
    const isAdmin = await this.checkAdminPermission(adminId)
    if (!isAdmin) {
      throw new Error('Admin permission required')
    }

    // 获取目标用户
    const targetUser = await prisma.user.findUnique({
      where: { id: userId }
    })

    if (!targetUser) {
      throw new Error('User not found')
    }

    // 检查权限：子管理员不能修改超级管理员和其他子管理员
    const adminUser = await prisma.user.findUnique({
      where: { id: adminId }
    })

    if (adminUser?.role === 'SUB_ADMIN') {
      if (targetUser.role === 'ADMIN' || targetUser.role === 'SUB_ADMIN') {
        throw new Error('Sub-admin cannot modify admin users')
      }
    }

    // 如果要修改角色，只有超级管理员可以操作
    if (data.role && adminUser?.role !== 'ADMIN') {
      throw new Error('Only super admin can change user roles')
    }

    // 检查邮箱唯一性
    if (data.email && data.email !== targetUser.email) {
      const existingUser = await prisma.user.findUnique({
        where: { email: data.email }
      })
      if (existingUser) {
        throw new Error('Email already exists')
      }
    }

    // 检查用户名唯一性
    if (data.username && data.username !== targetUser.username) {
      const existingUsername = await prisma.user.findUnique({
        where: { username: data.username }
      })
      if (existingUsername) {
        throw new Error('Username already exists')
      }
    }

    // 更新用户
    const updatedUser = await prisma.user.update({
      where: { id: userId },
      data,
      select: {
        id: true,
        email: true,
        username: true,
        role: true,
        isActive: true,
        googleId: true,
        avatar: true,
        payoutPassword: true,
        lastLoginAt: true,
        createdAt: true,
        updatedAt: true,
        createdByAdminId: true
      }
    })

    // 记录审计日志
    await this.logAuditAction(
      adminId,
      'UPDATE_USER',
      'User',
      `Updated user: ${updatedUser.email}`,
      userId
    )

    return updatedUser
  }

  /**
   * 删除用户
   */
  static async deleteUser(adminId: number, userId: number): Promise<void> {
    // 检查管理员权限
    const isAdmin = await this.checkAdminPermission(adminId)
    if (!isAdmin) {
      throw new Error('Admin permission required')
    }

    // 获取目标用户
    const targetUser = await prisma.user.findUnique({
      where: { id: userId }
    })

    if (!targetUser) {
      throw new Error('User not found')
    }

    // 检查权限：子管理员不能删除超级管理员和其他子管理员
    const adminUser = await prisma.user.findUnique({
      where: { id: adminId }
    })

    if (adminUser?.role === 'SUB_ADMIN') {
      if (targetUser.role === 'ADMIN' || targetUser.role === 'SUB_ADMIN') {
        throw new Error('Sub-admin cannot delete admin users')
      }
    }

    // 不能删除自己
    if (adminId === userId) {
      throw new Error('Cannot delete yourself')
    }

    // 删除用户
    await prisma.user.delete({
      where: { id: userId }
    })

    // 记录审计日志
    await this.logAuditAction(
      adminId,
      'DELETE_USER',
      'User',
      `Deleted user: ${targetUser.email}`,
      userId
    )
  }

  /**
   * 获取系统统计信息
   */
  static async getSystemStats(adminId: number): Promise<{
    totalUsers: number
    totalAdmins: number
    totalSubAdmins: number
    activeUsers: number
    totalRechargeRecords: number
    totalRechargeAmount: string
  }> {
    // 检查管理员权限
    const isAdmin = await this.checkAdminPermission(adminId)
    if (!isAdmin) {
      throw new Error('Admin permission required')
    }

    const [
      totalUsers,
      totalAdmins,
      totalSubAdmins,
      activeUsers,
      totalRechargeRecords,
      rechargeStats
    ] = await Promise.all([
      prisma.user.count(),
      prisma.user.count({ where: { role: 'ADMIN' } }),
      prisma.user.count({ where: { role: 'SUB_ADMIN' } }),
      prisma.user.count({ where: { isActive: true } }),
      prisma.rechargeRecord.count(),
      prisma.rechargeRecord.aggregate({
        _sum: { amount: true }
      })
    ])

    return {
      totalUsers,
      totalAdmins,
      totalSubAdmins,
      activeUsers,
      totalRechargeRecords,
      totalRechargeAmount: rechargeStats._sum.amount?.toString() || '0'
    }
  }

  /**
   * 获取快捷金额配置
   */
  static async getQuickAmounts(adminId: number): Promise<{ amounts: number[] }> {
    // 检查管理员权限
    const isAdmin = await this.checkAdminPermission(adminId)
    if (!isAdmin) {
      throw new Error('Admin permission required')
    }

    // 从系统设置表获取配置
    const setting = await prisma.systemSetting.findUnique({
      where: { key: 'recharge_quick_amounts' }
    })

    let amounts: number[] = [100, 500, 1000, 2000, 5000, 10000] // 默认值

    if (setting && setting.value) {
      try {
        amounts = JSON.parse(setting.value)
      } catch (error) {
        console.error('Failed to parse quick amounts config:', error)
      }
    }

    return { amounts }
  }


  /**
   * 获取购买价格信息配置
   */
  static async getPurchasePriceInfo(adminId: number): Promise<{ priceInfo: string }> {
    // 检查管理员权限
    const isAdmin = await this.checkAdminPermission(adminId)
    if (!isAdmin) {
      throw new Error('Admin permission required')
    }

    // 从系统设置表获取配置
    const setting = await prisma.systemSetting.findUnique({
      where: { key: 'purchase_price_info' }
    })

    let priceInfo: string = '5.5泰铢=1M金币' // 默认值

    if (setting && setting.value) {
      priceInfo = setting.value
    }

    return { priceInfo }
  }

  /**
   * 更新购买价格信息配置
   */
  static async updatePurchasePriceInfo(adminId: number, priceInfo: string): Promise<{ priceInfo: string }> {
    // 检查管理员权限
    const isAdmin = await this.checkAdminPermission(adminId)
    if (!isAdmin) {
      throw new Error('Admin permission required')
    }

    // 验证价格信息
    if (!priceInfo || priceInfo.trim().length === 0) {
      throw new Error('Price info cannot be empty')
    }

    const trimmedPriceInfo = priceInfo.trim()

    // 检查长度限制
    if (trimmedPriceInfo.length > 50) {
      throw new Error('Price info cannot exceed 50 characters')
    }

    // 更新或创建系统设置
    await prisma.systemSetting.upsert({
      where: { key: 'purchase_price_info' },
      update: { 
        value: trimmedPriceInfo,
        updatedAt: new Date()
      },
      create: {
        key: 'purchase_price_info',
        value: trimmedPriceInfo,
        description: '用户充值页面购买价格信息显示配置'
      }
    })

    // 记录审计日志
    await this.logAuditAction(
      adminId,
      'UPDATE_PURCHASE_PRICE_INFO',
      'SystemSetting',
      `Updated purchase price info: ${trimmedPriceInfo}`
    )

    return { priceInfo: trimmedPriceInfo }
  }

  /**
   * 更新快捷金额配置
   */
  static async updateQuickAmounts(adminId: number, amounts: number[]): Promise<{ amounts: number[] }> {
    // 检查管理员权限
    const isAdmin = await this.checkAdminPermission(adminId)
    if (!isAdmin) {
      throw new Error('Admin permission required')
    }

    // 验证金额数组
    if (!Array.isArray(amounts) || amounts.length === 0) {
      throw new Error('At least one amount is required')
    }

    // 验证每个金额都是正数
    for (const amount of amounts) {
      if (!Number.isFinite(amount) || amount <= 0) {
        throw new Error('All amounts must be positive numbers')
      }
    }

    // 去重并排序
    const uniqueAmounts = Array.from(new Set(amounts)).sort((a, b) => a - b)

    const configValue = JSON.stringify(uniqueAmounts)

    // 更新或创建系统设置
    await prisma.systemSetting.upsert({
      where: { key: 'recharge_quick_amounts' },
      update: { 
        value: configValue,
        updatedAt: new Date()
      },
      create: {
        key: 'recharge_quick_amounts',
        value: configValue,
        description: '用户充值页面快捷金额选项配置'
      }
    })

    // 记录审计日志
    await this.logAuditAction(
      adminId,
      'UPDATE_QUICK_AMOUNTS',
      'SystemSetting',
      `Updated quick amounts: [${uniqueAmounts.join(', ')}]`
    )

    return { amounts: uniqueAmounts }
  }

  /**
   * 获取产品配置列表
   */
  static async getProductConfigs(adminId: number): Promise<ProductConfig[]> {
    // 检查管理员权限
    const isAdmin = await this.checkAdminPermission(adminId)
    if (!isAdmin) {
      throw new Error('Admin permission required')
    }

    const configs = await prisma.productConfig.findMany({
      orderBy: { sortOrder: 'asc' }
    })

    return configs
  }

  /**
   * 更新产品配置
   */
  static async updateProductConfigs(adminId: number, configs: ProductConfigInput[]): Promise<ProductConfig[]> {
    // 检查管理员权限
    const isAdmin = await this.checkAdminPermission(adminId)
    if (!isAdmin) {
      throw new Error('Admin permission required')
    }

    // 验证配置数据
    if (!Array.isArray(configs) || configs.length === 0) {
      throw new Error('At least one product config is required')
    }

    // 验证每个配置
    for (const config of configs) {
      if (!Number.isFinite(config.coinAmount) || config.coinAmount <= 0) {
        throw new Error('Coin amount must be a positive number')
      }
      if (!Number.isFinite(config.productId) || config.productId <= 0) {
        throw new Error('Product ID must be a positive number')
      }
      if (!Number.isFinite(config.sortOrder) || config.sortOrder < 0) {
        throw new Error('Sort order must be a non-negative number')
      }
    }

    // 检查金币数量唯一性
    const coinAmounts = configs.map(c => c.coinAmount)
    const uniqueCoinAmounts = new Set(coinAmounts)
    if (coinAmounts.length !== uniqueCoinAmounts.size) {
      throw new Error('Coin amounts must be unique')
    }

    // 检查产品ID唯一性
    const productIds = configs.map(c => c.productId)
    const uniqueProductIds = new Set(productIds)
    if (productIds.length !== uniqueProductIds.size) {
      throw new Error('Product IDs must be unique')
    }

    try {
      // 使用事务更新所有配置
      const updatedConfigs = await prisma.$transaction(async (tx) => {
        // 删除所有现有配置
        await tx.productConfig.deleteMany({})

        // 批量插入新配置
        const results: ProductConfig[] = []
        for (const config of configs) {
          const created = await tx.productConfig.create({
            data: {
              coinAmount: config.coinAmount,
              productId: config.productId,
              isActive: config.isActive,
              description: config.description || `${config.coinAmount}M金币`,
              sortOrder: config.sortOrder
            }
          })
          results.push(created)
        }

        return results.sort((a, b) => a.sortOrder - b.sortOrder)
      })

      // 记录审计日志
      await this.logAuditAction(
        adminId,
        'UPDATE_PRODUCT_CONFIGS',
        'ProductConfig',
        `Updated ${configs.length} product configurations`
      )

      return updatedConfigs
    } catch (error) {
      throw new Error(`Failed to update product configurations: ${error instanceof Error ? error.message : 'Unknown error'}`)
    }
  }

  /**
   * 获取活跃产品配置（公开接口）
   */
  static async getActiveProductConfigs(): Promise<ProductConfig[]> {
    const configs = await prisma.productConfig.findMany({
      where: { isActive: true },
      orderBy: { sortOrder: 'asc' }
    })

    return configs
  }

  /**
   * 记录审计日志
   */
  private static async logAuditAction(
    userId: number,
    action: string,
    resource: string,
    details: string,
    targetUserId?: number,
    ipAddress?: string,
    userAgent?: string
  ): Promise<void> {
    try {
      const logDetails = targetUserId 
        ? `${details} (Target User ID: ${targetUserId})`
        : details

      await prisma.auditLog.create({
        data: {
          userId,
          action,
          resource,
          details: logDetails,
          ipAddress,
          userAgent
        }
      })
    } catch (error) {
      console.error('Failed to log audit action:', error)
    }
  }
}
